<?php


namespace api\user\controller;


use api\user\model\AddressModel;
use api\user\model\LoginModel;
use api\user\validate\AddressValidate;
use api\user\validate\UserValidate;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Filesystem;
use think\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UserController extends RestBaseController
{
    //注册api
    public function register(Request $request)
    {
        $data = $request->param();
        //验证器
        $admin = LoginModel::where('mobile','=',$data['mobile'])
            ->find();
        if(!empty($admin))
        {
            $this->error('该手机号已注册');
        }
        $validate = new UserValidate();
        $val = $validate->scene('register')->check($data);
        if(!$val)
        {
            $this->error($validate->getError());
        }

        //验证验证码
        CheckSmsCode($data['mobile'], $data['code']);
        //入库
        $res = LoginModel::create($data);
        if($res)
        {
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }
    //登录api
    public function login(Request $request)
    {
        $mobile = $request->param('mobile');
        $code = $request->param('code');

        if(empty($mobile))
        {
            $this->error('手机号码不能为空');
        }
        if(empty($code)){
            $this->error('验证码不能为空');
        }
        $res = LoginModel::where('mobile','=',$mobile)
            ->find();
        //halt($res);
        if(empty($res))
        {
            $this->error('手机号错误');
        }
        if(CheckSmsCode($mobile, $code)) {
            $this->error('验证码错误');
        }
        $token = sendToken($res['id'],$mobile);
        $this->success(
            '登录成功',
            [
                'data'=>$token
            ]
        );
    }
    public function SentCode(Request $request)
    {
        $mobile = $request->param('mobile');
        //发送验证码
        sendAliSms($mobile);
    }
    //查找
    public function SelectAdmin(Request $request)
    {
        $token = $request->header();
        if(!isset($token['token']) || empty($token['token']))
        {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($token['token'],$key);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $data = LoginModel::where('id','=',$res->data->user_id)
            ->find();
        $this->success('用户信息',
            [
                'res'=>$data
            ]);
    }
    //上传图片
    public function SentImage(Request $request)
    {
        $image = $request->file('image');
        $image = Filesystem::disk('public')->putFile('image', $image);
        if($image)
        {
            $this->success('图片地址',
                ['image'=>$request->domain().'/strong'.$image]);
        }
    }
    //七牛云
    public function uploadToQiniu(Request $request)
    {
        $accessKey = Config('app.qiniuoss.accessKey');
        $secretKey = Config('app.qiniuoss.secretKey');
        $bucket = Config('app.qiniuoss.bucket');
        $file = $request->file('file');
        if (!empty($file)) {
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 生成上传 Token
            $token = $auth->uploadToken($bucket);
            // 要上传文件的本地路径
            $filePath = $file->getPathname();
            // 上传到七牛后保存的文件名
            $key = time().'.'.$file->getOriginalName();
            // 初始化 UploadManager 对象并进行文件的上传。
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传。
            list($return, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return $err; // 失败
            } else {
                return $key; // 成功，$key 就是在七牛云的文件名，加上你在七牛云的外链地址就可以访问到文件
            }
        }
    }
    //更新账号信息
    public function UpdateAdmin(Request $request)
    {
        $user_name = $request->param('user_name');
        $mobile = $request->param('mobile');
        $image = $request->param('image');
        $res = LoginModel::where('mobile','=',$mobile)
            ->update([
                'user_image'=>$image,
                'name'=>$user_name
            ]);
        if(!empty($res))
        {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    //查看收货地址
    public function address(Request $request)
    {
        $token = $request->header();
        if(!isset($token['token']) || empty($token['token']))
        {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'),'HS256');

        try {
            $res = JWT::decode($token['token'],$key);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $page = input('page/d',1);
        $pageSize = input('page_size/d',10);
        $list = AddressModel::field('mobile,address_user,address,address_detalied')
            ->order('id','desc')
            ->where('mobile','=',$res->data->mobile)
            ->page($page,$pageSize)
            ->select();

        $this->success('收货信息列表',$list);
    }
    //添加收货地址
    public function AddAddress()
    {
        $data = input();
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['create_time'] = date('Y:m:d H:i:s');
        //halt($data);
        $add = AddressModel::create($data);
        if($add){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }
    //修改收货地址
    public function updateAddress()
    {
        $data = input();
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['update_time'] = date('Y:m:d H:i:s');
        $edit = AddressModel::where('id','=',$data['id'])
            ->update($data);
        if($edit){
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }
    //删除
    public function DeleteAddress($id)
    {
        $news = AddressModel::find($id);
        if (!$news) {
            $this->error('地址不存在');
        }

        if ($news->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    //支付
    public function money(Request $request)
    {
        $money = $request->param('money');
        if(!$money)
        {
            $this->error('请输入金额');
        }
        $user = LoginModel::find($request->user_id);
        if(!$user)
        {
            $this->error('参数错误');
        }
        $after = $user['wallet'] + $money;
        // 启动事务
        Db::startTrans();
        $res = false;
        $log = false;
        try {
            $res = money_log($request->user_id,$money,$user['wallet'],$after,'1');
            $log = LoginModel::where('id','=',$request->user_id)->update(['wallet'=>$after]);
        } catch (\Exception $e) {
            // 回滚
            Db::rollback();
        }
        if ($res && $log) {
            // 提交
            Db::commit();
            $this->success('充值成功');
        } else {
            // 回滚
            Db::rollback();
            $this->error('充值成功');
        }

    }
}